package com.xuecheng.media.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.xuecheng.api.media.model.AliyunVodApi;
import com.xuecheng.api.media.model.aliyun.VodUploadRequest;
import com.xuecheng.api.media.model.aliyun.VodUploadToken;
import com.xuecheng.media.common.utils.AliyunVODUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *
 * </p>
 *
 * @Description:
 */
@Slf4j
@RestController
public class AliyunVodController implements AliyunVodApi {

    /*
    * aliyun.region = cn-shanghai
    aliyun.accessKeyId = LTAI4G3wMNtzQPfFPDMHoCJF
    aliyun.accessKeySecret = uxzY3N4czSqZqhcXcuOq0ZcRlB6zjB
    * */
    @Value("${aliyun.region}")
    private String region;
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;


    @PostMapping("media/vod-token")
    public VodUploadToken generateUploadToken(@RequestBody VodUploadRequest request) {

        VodUploadToken token = null;
        // 项目中只要访问外部的服务内容，必须要加try-catch
        // 原因：网络（网络抖动：1.连接超时  2.连接失败）
        // 外部的错误信息，一定要进行日志的记录和返回默认的错误数据
        try {
            // 1.获得client对象
            DefaultAcsClient client = AliyunVODUtil.initVodClient(region, accessKeyId, accessKeySecret);

            // 2.获得response对象
            CreateUploadVideoResponse videoResponse = AliyunVODUtil.createUploadVideo(client, request.getTitle(), request.getFileName());

            // 3.解析数据并封装结果
            token = new VodUploadToken();
            token.setUploadAuth(videoResponse.getUploadAuth());
            token.setRequestId(videoResponse.getRequestId());
            token.setUploadAddress(videoResponse.getUploadAddress());
            token.setVideoId(videoResponse.getVideoId());
            return token;
        } catch (Exception e) {

            //e.printStackTrace();  如果业务出错，并且请求量很大，直接导致服务器宕机：io阻塞
            // 处理的手段：1.返回默认数据并记录错误信息（本项目）   2.记录错误信息，并将异常向外抛出
            log.error("获得阿里云上传文件凭证失败：{}", e.getMessage());
            token = new VodUploadToken();
            return token;
        }

    }

    @GetMapping("media/refresh-vod-token/{videoId}")
    public VodUploadToken refreshUploadToken(@PathVariable String videoId) {

        VodUploadToken token = null;
        try {
            // 1.获得client对象
            DefaultAcsClient client = AliyunVODUtil.initVodClient(region, accessKeyId, accessKeySecret);

            // 2.获得response对象
            RefreshUploadVideoResponse uploadVideo = AliyunVODUtil.refreshUploadVideo(client, videoId);

            // 3.解析数据并封装结果
            token = new VodUploadToken();
            token.setUploadAuth(uploadVideo.getUploadAuth());
            token.setRequestId(uploadVideo.getRequestId());
            token.setUploadAddress(uploadVideo.getUploadAddress());
            token.setVideoId(uploadVideo.getVideoId());

            return token;
        } catch (Exception e) {
            //e.printStackTrace();  如果业务出错，并且请求量很大，直接导致服务器宕机：io阻塞
            // 处理的手段：
            // 1.返回默认数据并记录错误信息（本项目）
            // 2.记录错误信息，并将异常向外抛出
            log.error("获得阿里云上传文件凭证失败：{}", e.getMessage());
            token = new VodUploadToken();

            // 将系统异常转为业务异常
            // log.error("获得阿里云上传文件凭证失败：{}",e.getMessage());
            // ExceptionCast.cast(MediaErrorCode.E_140012);
            return token;
        }

    }

}
